package other;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

public class UDPSocketManager {
    private ServerSocket server;
    private Handler handler = null;

    public UDPSocketManager(Handler handler) {
        this.handler = handler;
        int port = 9999;

        try {
            // 1.新建ServerSocket对象，创建指定端口的连接
            server = new ServerSocket(port);
        } catch (Exception e) {

        }

        sendMessage(1, port);

        Thread receiveFileThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    ReceiveFile();
                }
            }
        });
        receiveFileThread.start();
    }

    private void sendMessage(int what, Object obj) {
        if (handler != null) {
            Message.obtain(handler, what, obj).sendToTarget();
        }
    }

    private void ReceiveFile() {

		/*
        在使用TCP编程的时候，最后需要释放资源，关闭socket(socket.close())；关闭socket输入输出流
		（socket.shutdownInput()以及socket.shutdownOutput()）；关闭IO流(is.close() os.close())。
		需要注意的是：关闭socket的输入输出流需要放在关闭io流之前。因为， 关闭IO流会同时关闭socket，
		一旦关闭了socket的，就不能再进行socket的相关操作了。而，只关闭socket输入输出流（socket.shutdownInput()
		以及socket.shutdownOutput()）不会完全关闭socket，此时任然可以进行socket方面的操作。
		所以要先调用socket.shutdownXXX，然后再调用io.close();

		 */

        try {
            // 2.进行监听,开始监听xxxx端口，并接收到此套接字的连接。
            Socket nameSocket = server.accept();
            // 3.拿到输入流（客户端发送的信息就在这里）
            InputStream nameInputStream = nameSocket.getInputStream();
            // 4.解析数据
            InputStreamReader streamReader = new InputStreamReader(nameInputStream);
            BufferedReader bufferedReader = new BufferedReader(streamReader);
            String fileName = bufferedReader.readLine();

            // 关闭输入流
            nameSocket.shutdownInput();

            // 关闭IO资源
            bufferedReader.close();
            streamReader.close();
            nameInputStream.close();
            // 关闭socket
            nameSocket.close();

            sendMessage(0, "正在接收:" + fileName);

            Socket dataSocket = server.accept();
            InputStream dataInputStream = dataSocket.getInputStream();
            String pathString = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;
            String pathMD5 = MD5Util.getFileMD5String(pathString);
            // 4.解析数据
            FileOutputStream fileOutputStream = new FileOutputStream(pathString, false);
            byte[] buffer = new byte[1024];
            int size = -1;
            while ((size = dataInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, size);
            }

            // 关闭输入流
            dataSocket.shutdownInput();

            // 关闭输出流
            dataSocket.shutdownOutput();

            dataInputStream.close();
            fileOutputStream.close();

            dataSocket.close();

            sendMessage(0, fileName + "接收完成" + "-MD5:" + pathMD5);
        } catch (Exception e) {
            sendMessage(0, "接收错误:\n" + e.getMessage());
        }
    }

    public void SendFile(ArrayList<String> fileName, ArrayList<String> path, String ipAddress, int port) {
        try {
            for (int i = 0; i < fileName.size(); i++) {

                Socket nameSocket = new Socket(ipAddress, port);

                OutputStream nameOutputStream = nameSocket.getOutputStream();
                OutputStreamWriter outputWriter = new OutputStreamWriter(nameOutputStream);
                BufferedWriter bufferedWriter = new BufferedWriter(outputWriter);
                //写入要发送给服务器的数据
                bufferedWriter.write(fileName.get(i));
                bufferedWriter.close();
                outputWriter.close();
                nameOutputStream.close();
                nameSocket.close();
                sendMessage(0, "正在发送:" + fileName.get(i));


                //1.创建监听指定服务器地址以及指定服务器监听的端口号
                Socket dataSocket = new Socket(ipAddress, port);
                //2.拿到客户端的socket对象的输出流发送给服务器数据
                OutputStream dataOutputStream = dataSocket.getOutputStream();
                FileInputStream fileInput = new FileInputStream(path.get(i));
                int size = -1;
                byte[] buffer = new byte[1024];
                while ((size = fileInput.read(buffer, 0, 1024)) != -1) {
                    //写入要发送给服务器的数据
                    dataOutputStream.write(buffer, 0, size);
                }

                String pathMD5 = MD5Util.getFileMD5String(path.get(i));

                dataOutputStream.close();
                fileInput.close();
                dataSocket.close();
                sendMessage(0, fileName.get(i) + "发送完成" + "-pathMD5:" + pathMD5);
            }
            sendMessage(0, "所有文件发送完成");
        } catch (Exception e) {
            sendMessage(0, "发送错误:\n" + e.getMessage());
        }
    }
}
